package com.example.testappwidget.widgetprovider

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.IBinder
import android.widget.RemoteViews
import androidx.annotation.RequiresApi
import com.example.testappwidget.R
import com.example.testappwidget.ui.activity.MainActivity
import com.example.testappwidget.utils.LogUtil


/*
 *Author: chinadragon
 *Time: 2024/3/30
 * android电量显示动画 安卓显示电量的小组件
 * https://blog.51cto.com/u_16099264/7465609
 */
class NewBatteryWidget : AppWidgetProvider() {
    val TAG = this.javaClass.simpleName

    companion object {
        const val UNKONW = -1
        var currentBatteryLevel = UNKONW
        var currentBatteryStatus = UNKONW
    }

    /**
     * 此方法会根据配置的 updatePeriodMillis 属性定义的时间间隔进行调用，作用为更新小部件，当用户添加小部件时也会调用此方法，
     * 因此它应该执行一些基本的设置。但是，如果你已经声明了一个ConfigureActivity，这个方法在用户添加小部件时不会调用，而是在后续更新时调用。
     * ConfigureActivity负责在配置完成后执行第一次更新。
     *
     * 原文链接：https://blog.csdn.net/hwb04160011/article/details/119728412
     */
//    @RequiresApi(Build.VERSION_CODES.O)
    override fun onUpdate(context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray?) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)
        if (context == null){
            return
        }
        LogUtil.i(TAG,"onUpdate context 名称：${context.javaClass.simpleName}")
        //启动自动更新电池信息的service
        context.startService(Intent(context, UpdateService::class.java))
//        context.startForegroundService(Intent(context, UpdateService::class.java))

        //为AppWidget设置点击事件的响应，启动显示电池信息详情的activity
        val startActivityIntent = Intent(context, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(context,0,startActivityIntent, PendingIntent.FLAG_IMMUTABLE)
        val views =  RemoteViews(context.getPackageName() ,R.layout.newrelativelayout)
        views.setOnClickPendingIntent(R.id.imageView,pendingIntent)
        appWidgetManager?.updateAppWidget(appWidgetIds,views)
    }

    /**
     * 只有在桌面上添加对应小部件的第一个实例时会调用此方法。例如，如果用户连续添加了一个小部件两次，只有第一次添加时会调用此方法。
     *
     * 原文链接：https://blog.csdn.net/hwb04160011/article/details/119728412
     */
    override fun onEnabled(context: Context?) {
        super.onEnabled(context)
    }

    /**
     * 当对应小部件的最后一个实例从 App Widget 主机中删除时，会调用此方法，在此方法中应执行资源释放等工作。
     */
    override fun onDisabled(context: Context?) {
        super.onDisabled(context)
    }

    /**
     * 每次从桌面删除小部件时都会调用此方法。
     */
    override fun onDeleted(context: Context?, appWidgetIds: IntArray?) {
        super.onDeleted(context, appWidgetIds)
    }

     class UpdateService : Service() {
        val Tag = this.javaClass.simpleName
         val NOTIFICATION_ID = 1
         val channel_id = "test_widget"
         val channel_name = "test_widget_组件"

         /**
          *电池信息广播接收者
          */
         private val mBatteryReceiver: BroadcastReceiver = object : BroadcastReceiver() {

             override fun onReceive(context: Context?, intent: Intent?) {
                 if (intent == null) {
                     LogUtil.i(Tag,"mBatteryReceiver onReceive 回调 intent 为null")
                     return
                 }
                 currentBatteryLevel = intent.getIntExtra("level", UNKONW)
                 currentBatteryStatus = intent.getIntExtra("status", UNKONW)
                 LogUtil.i(Tag,"mBatteryReceiver onReceive 回调 intent.action: ${intent.action} , currentBatteryLevel = $currentBatteryLevel, currentBatteryStatus = $currentBatteryStatus")
                 updateRemoteViews(context)
             }
         }

        override fun onCreate() {
            super.onCreate()
            LogUtil.i(Tag,"onCreate 回调")
        }

        override fun onRebind(intent: Intent?) {
            super.onRebind(intent)
        }

        override fun onBind(intent: Intent?): IBinder? {
            return null
        }

        @RequiresApi(Build.VERSION_CODES.O)
        override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
            LogUtil.i(Tag,"onStartCommand 回调")

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(channel_id, channel_name, NotificationManager.IMPORTANCE_DEFAULT)
                val notificationManager = getSystemService(NotificationManager::class.java)
                notificationManager.createNotificationChannel(channel)
            }

            val notificationIntent = Intent(this, MainActivity::class.java)
            val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE)

            val  notification =  Notification.Builder(this,channel_id)
                .setContentTitle("TestWidget App正在运行")
                .setContentText("点击返回App")
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.ic_launcher_background).build();


            // 开启前台服务  需要前台服务权限
            startForeground(NOTIFICATION_ID,notification)
            //注册接收器
            registerReceiver(mBatteryReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
            return super.onStartCommand(intent, flags, startId)
        }

        override fun onUnbind(intent: Intent?): Boolean {
            return super.onUnbind(intent)
        }

        override fun onDestroy() {
            super.onDestroy()
            LogUtil.i(Tag,"onDestroy 回调")
        }

        private fun updateRemoteViews(context: Context?){
             if (context == null){
                 LogUtil.i(Tag,"mBatteryReceiver onReceive context 为null")

                 return
             }

             //定义一个RemoteViews，实现对AppWidget界面控制
             val views = RemoteViews(context.packageName, R.layout.newrelativelayout)
             var bmp: Bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher)
//             var bmp: Bitmap? = null //定义机器人图片

//            if (currentBatteryStatus == 2 || currentBatteryStatus == 5) {//当正在充电或充满电时，显示充电的图片
//                 if (currentBatteryLevel >= 95) {
//                     bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_background)
//                 }
//             } else {//未在充电时，显示不在充电状态的系列图片
//                 if (currentBatteryLevel >= 95) {
//                     bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_background)
//                 }
//             }

             //设置AppWidget上显示的图片和文字的内容
             views.setImageViewBitmap(R.id.imageView, bmp)
             views.setTextViewText(R.id.tv, "$currentBatteryLevel%")

             val thisWidget = ComponentName(context, NewBatteryWidget::class.java)
             //使用AlarmManager实现每隔一秒发送一次更新提示信息，实现信息实时动态变化
             val now = System.currentTimeMillis()
             val pause = 60000

             var alarmIntent = Intent()


//            val pendingIntent = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_IMMUTABLE)
//            val alarm = getSystemService(Context.ALARM_SERVICE) as AlarmManager
//            alarm.set(AlarmManager.RTC_WAKEUP,now+pause, pendingIntent)

             //定义一个 AppWidgetManager
             val appWidgetManager = AppWidgetManager.getInstance(context)

             //更新AppWidget
             appWidgetManager.updateAppWidget(thisWidget,views)
         }

    }
}
